<?php

namespace App\Orchid\Screens\Tag;

use App\Models\Tag;
use Illuminate\Http\Request;
use Orchid\Screen\Screen;
use Orchid\Screen\Fields\Input;
use Orchid\Screen\Actions\Button;
use Orchid\Support\Facades\Toast;
use Orchid\Support\Facades\Layout;
use Illuminate\Support\Str;

class TagEditScreen extends Screen
{
    /**
     * @var Tag
     */
    public $tag;

    /**
     * Fetch data to be displayed on the screen.
     *
     * @param Tag $tag
     *
     * @return array
     */
    public function query(Tag $tag): iterable
    {
        return [
            'tag' => $tag,
        ];
    }

    /**
     * The name of the screen displayed in the header.
     */
    public function name(): ?string
    {
        return $this->tag->exists ? '编辑标签' : '新建标签';
    }

    /**
     * Display header description.
     */
    public function description(): ?string
    {
        return $this->tag->exists ? '编辑现有标签信息' : '创建新的文章标签';
    }

    /**
     * The screen's action buttons.
     *
     * @return \Orchid\Screen\Action[]
     */
    public function commandBar(): iterable
    {
        return [
            Button::make('保存')
                ->icon('check')
                ->method('save'),

            Button::make('删除')
                ->icon('trash')
                ->method('remove')
                ->canSee($this->tag->exists)
                ->confirm('确定要删除这个标签吗？'),
        ];
    }

    /**
     * The screen's layout elements.
     *
     * @return \Orchid\Screen\Layout[]
     */
    public function layout(): iterable
    {
        return [
            Layout::rows([
                Input::make('tag.name')
                    ->title('标签名称')
                    ->placeholder('输入标签名称')
                    ->required()
                    ->help('标签的显示名称'),

                Input::make('tag.slug')
                    ->title('Slug')
                    ->placeholder('自动生成或手动输入')
                    ->help('URL友好的标识符，留空将自动生成'),
            ]),
        ];
    }

    /**
     * Save tag
     *
     * @param Request $request
     * @param Tag $tag
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function save(Request $request, Tag $tag)
    {
        $request->validate([
            'tag.name' => 'required|string|max:255',
            'tag.slug' => 'nullable|string|max:255|unique:tags,slug,' . $tag->id,
        ]);

        $data = $request->get('tag');
        
        // 自动生成slug
        if (empty($data['slug'])) {
            $data['slug'] = Str::slug($data['name']);
        }
        
        // 确保slug唯一
        $data['slug'] = $this->ensureUniqueSlug($data['slug'], $tag->id);

        $tag->fill($data)->save();

        Toast::info('标签已保存');

        return redirect()->route('platform.tags');
    }

    /**
     * Remove tag
     *
     * @param Tag $tag
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function remove(Tag $tag)
    {
        // 检查是否有关联的文章
        if ($tag->posts()->count() > 0) {
            Toast::error('无法删除包含文章的标签');
            return back();
        }
        
        $tag->delete();

        Toast::info('标签已删除');

        return redirect()->route('platform.tags');
    }
    
    /**
     * Ensure slug is unique
     *
     * @param string $slug
     * @param int|null $excludeId
     * @return string
     */
    private function ensureUniqueSlug(string $slug, ?int $excludeId = null): string
    {
        $originalSlug = $slug;
        $counter = 1;
        
        while (Tag::where('slug', $slug)
            ->when($excludeId, fn($query) => $query->where('id', '!=', $excludeId))
            ->exists()) {
            $slug = $originalSlug . '-' . $counter;
            $counter++;
        }
        
        return $slug;
    }
}